import { Component, OnInit, Inject, forwardRef, ChangeDetectorRef, ViewChild } from '@angular/core';
import { ModalDirective } from 'ngx-bootstrap';
import { FileUploader } from '../../../../../lib/ng2-file-upload';

import { AppComponent } from '../../../../app.component';
import { ActivityGoodsManagementGridComponent } from '../activity-goods-management-grid/activity-goods-management-grid.component';

import { masterService } from '../../../../../lib/master.service';
import { path } from '../../../../path.config';

@Component({
    selector: 'app-activity-goods-management-add-modal',
    templateUrl: './activity-goods-management-add-modal.component.html',
    styleUrls: ['./activity-goods-management-add-modal.component.css'],
    providers: [forwardRef(() => AppComponent),
    forwardRef(() => ActivityGoodsManagementGridComponent)]
})
export class ActivityGoodsManagementAddModalComponent implements OnInit {
    @ViewChild('SearchGoogsSn') public SearchGoodsSn: ModalDirective;
    // api地址定义
    // 上传图片
    private addImgItem = path.imagesUpload.apiUrl;
    // 获取图片id
    private getImgId = path.imagesUpload.getImgId;
    // 创建活动配置
    private createActivity = path.campaignManage.activityGoods.createItem;
    // 编辑活动配置
    private editActivity = path.campaignManage.activityGoods.editItem;
    // 添加活动商品时查询商品信息列表
    private goodsSninfo = path.campaignManage.activityGoods.goodsSninfo;

    // 列表项数组
    public rows: Array<any> = [];
    // 表格数据头部标题
    public columns: Array<any> = [
        { title: '商品Sn', name: '' },
        { title: '商品名称', name: '' },
        { title: '操作', name: '' },
    ];
    // 当前页码
    public page: any = 1;
    // 一共多少页
    public itemsPerPage: number = 10;
    // 分页最多显示的页数
    public maxSize: number = 5;
    // 总页数计数变化时，事件数等于总页数计数
    public numPages: number = 1;
    // 总共的列表项数
    public totalItems: number = 0;
    // 分页器的文本配置
    public localText = {
        firstBtn: '首页',
        lastBtn: '末页',
        previousBtn: '上一页',
        nextBtn: '下一页'
    }

    // 上传图片插件对象
    BreviaryPicUpload: FileUploader = new FileUploader({
        url: this.addImgItem,
        method: 'post',
        itemAlias: 'uploadedFile'
    })

    BackgroundPicUpload: FileUploader = new FileUploader({
        url: this.addImgItem,
        method: 'post',
        itemAlias: 'uploadedFile'
    })

    uploadPic = {};

    public setModel = {
        id: '',
        goodsGuid: '',
        goodsSn: '',
        goodsName: '',
        marketPrice: '',
        activityPrice: '',
        breviaryPicUrl: '',
        backgroundPicUrl: '',
        breviaryImageId: '',
        backgroundImageId: ''
    }

    constructor(private _masterService: masterService,
        private cdRef: ChangeDetectorRef,
        @Inject(forwardRef(() => AppComponent)) public app: AppComponent,
        @Inject(forwardRef(() => ActivityGoodsManagementGridComponent)) public ActivityGoods: ActivityGoodsManagementGridComponent) { }

    ngOnInit() { }

    public onChangeTable(page: any = {
        itemsPerPage: this.itemsPerPage,
        page: this.page
    }): any {
        // get传入的参数
        let urlObject = {
            keyword: this.setModel.goodsSn,
            pageSize: page.itemsPerPage,
            pageIndex: page.page
        }
        this._masterService
            .getData(this.goodsSninfo, urlObject)
            .subscribe((res) => {
                if (res.statusCode == 200) {
                    this.rows = res.data.items;
                    this.totalItems = res.data.pagination.totalCount;
                    this.itemsPerPage = res.data.pagination.pageSize;
                    this.page = parseInt(res.data.pagination.pageIndex);
                    this.cdRef.detectChanges();
                } else if (res.statusCode == 401) {
                    this.app.logOff();
                } else {
                    this.app.toastError('错误信息： ' + res.errorMessage);
                }
            })
    }

    // 上传
    uploadFile(uploader?, uploadType?) {
        let thisItem = (uploader.length == 1) ? uploader.queue[0] : uploader.queue[uploader.queue.length - 1];
        let that = this;
        if (thisItem == undefined) {
            this.app.toastWarning("请选择图片");
            return;
        }

        thisItem.withCredentials = false;
        // 成功回调
        thisItem.onSuccess = function (response, status, headers) {
            // 上传文件成功
            if (status == 200) {
                // 上传文件后获取服务器返回的数据
                let tempRes = JSON.parse(response);
                that.uploadPic = {
                    imageName: thisItem.some.name,
                    imageUrl: tempRes.data.url[0],
                    extension: thisItem.some.type.split('/')[thisItem.some.type.split('/').length - 1],
                    imageSize: thisItem.some.size + 'B',
                    resolution: thisItem.resolution
                }
                that._masterService
                    .postData(that.getImgId, that.uploadPic)
                    .subscribe((res) => {
                        if (res.statusCode == 200) {
                            if (uploadType == 0) {
                                that.setModel.breviaryImageId = res.data;
                                that.setModel.breviaryPicUrl = tempRes.data.url[0];
                            } else if (uploadType == 1) {
                                that.setModel.backgroundImageId = res.data;
                                that.setModel.backgroundPicUrl = tempRes.data.url[0];
                            }
                            that.app.toastSuccess('上传成功！');
                            that.cdRef.detectChanges();
                        } else {
                            that.app.toastError('错误信息：' + res.errorMessage)
                        }
                    })
            } else {
                // 上传文件后获取服务器返回的数据错误
                that.app.toastError('错误信息：' + response.errorMessage);
            }
        };

        thisItem.onError = function (response, status, headers) {
            // 错误回调
            that.app.toastError('错误信息：' + response.errorMessage)
        };

        thisItem.upload(); // 开始上传
    }

    selectedFileOnChanged(event: any, uploader) {
        let $this = this;
        let thisItem = uploader.queue[0] = uploader.queue[uploader.queue.length - 1];
        let reader = new FileReader();
        reader.readAsDataURL(thisItem.some);
        reader.onload = function (e) {
            thisItem.src = this.result;
            var img = new Image();
            img.src = thisItem.src;
            img.onload = function () {
                // 存图片的分辨率
                thisItem.resolution = img.width + '*' + img.height;
            }
        }
        this.cdRef.detectChanges();
    }

    saveActivity() {
        if (!this.setModel.goodsSn) {
            this.app.toastWarning('请输入商品sn！');
            return;
        } else if (!this.setModel.goodsName) {
            this.app.toastWarning('请输入商品名称！');
            return;
        } else if (!this.setModel.marketPrice) {
            this.app.toastWarning('请输入市场价格');
            return;
        } else if (!(/^\d+(\.\d{1,2})?$/.test(this.setModel.marketPrice))) {
            this.app.toastWarning('市场价限输非负数，支持2位小数！');
            return;
        } else if (!this.setModel.activityPrice) {
            this.app.toastWarning('请输入活动价格！');
            return;
        } else if (!(/^\d+(\.\d{1,2})?$/.test(this.setModel.activityPrice))) {
            this.app.toastWarning('活动价限输非负数，支持2位小数！');
            return;
        } else if (!this.setModel.breviaryImageId) {
            this.app.toastWarning('请上传商品缩略图！');
            return;
        } else if (!this.setModel.backgroundImageId) {
            this.app.toastWarning('请上传背景图！');
            return;
        } else if (!this.setModel.goodsGuid) {
            this.app.toastWarning('请选择查询的商品sn！');
            return;
        }

        this._masterService
            .postData(this.createActivity, this.setModel)
            .subscribe((res) => {
                if (res.statusCode == 200) {
                    this.app.toastSuccess('新建成功');
                    this._masterService
                        .closeActivity
                        .emit();
                    this._masterService.ActivityReload.emit();
                } else if (res.statusCode == 401) {
                    this.app.logOff();
                } else {
                    this.app.toastError('错误信息： ' + res.errorMessage);
                }
            })
    }

    searchSn() {
        this.SearchGoodsSn.show();
        this.onChangeTable();
    }

    selectGoods(row) {
        this.SearchGoodsSn.hide();
        this.setModel.goodsGuid = row.goodsGuid;
        this.setModel.goodsName = row.goodsName;
        this.setModel.goodsSn = row.goodsSn;
    }
}
